<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1440">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="检验单号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联订单" prop="linkNo" :disabled="true">
            <el-input v-model="formData.linkNo" readonly>
              <template #append>
                <el-button>
                  <Icon icon="ep:search"/>
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验数量" prop="count">
            <el-input v-model="formData.count" placeholder="请输入检验数量"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="供应商" prop="supplierId">
            <ErpSelectSupplier v-model="formData.supplierId" placeholder="请选择供应商"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验时间" prop="checkTime">
            <el-date-picker
              v-model="formData.checkTime"
              type="date"
              value-format="x"
              placeholder="选择检验时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="产品数据" prop="productData">
        <el-table :data="productData" border style="width: 100%" size="small">
          <el-table-column label="序号" type="index" width="60" align="center"/>
          <el-table-column label="名称" align="center" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="请输入名称"/>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" :min="0" :controls="false"
                               style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column label="性能" align="center" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.performance" placeholder="请输入性能"/>
            </template>
          </el-table-column>
          <el-table-column label="尺寸" align="center" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.size" placeholder="请输入尺寸"/>
            </template>
          </el-table-column>
          <el-table-column label="抽检数量" align="center" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.sampleCount"
                :min="0"
                :controls="false"
                style="width: 100%"
                @change="calculateProductDefectRate(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="不合格数量" align="center" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.defectCount"
                :min="0"
                :max="row.sampleCount"
                :controls="false"
                style="width: 100%"
                @change="calculateProductDefectRate(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="不良率" align="center" width="80">
            <template #default="{ row }">
              {{ row.defectRate || '0%' }}
            </template>
          </el-table-column>
          <el-table-column label="判定结果" align="center" width="120">
            <template #default="{ row }">
              <el-select v-model="row.result" placeholder="请选择">
                <el-option label="合格" value="合格"/>
                <el-option label="不合格" value="不合格"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80" fixed="right">
            <template #default="{ $index }">
              <el-button
                link
                type="danger"
                @click="removeProductRow($index)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          plain
          @click="addProductRow"
          style="margin-top: 10px; width: 100%"
          :icon="Plus"
        >
          添加产品
        </el-button>
      </el-form-item>

      <el-form-item label="检验数据" prop="checkData">
        <el-table :data="checkData" border style="width: 100%" size="small">
          <el-table-column label="序号" type="index" width="60" align="center"/>
          <el-table-column label="检验项目" align="center" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.item" placeholder="请输入检验项目"/>
            </template>
          </el-table-column>
          <el-table-column label="标准" align="center" min-width="180">
            <template #default="{ row }">
              <el-input
                type="textarea"
                v-model="row.standard"
                placeholder="请输入标准"
                :autosize="{ minRows: 2, maxRows: 4 }"
                style="font-size: 12px"
              />
            </template>
          </el-table-column>
          <el-table-column label="抽检数量" align="center" width="90">
            <template #default="{ row }">
              <el-input-number
                v-model="row.sampleCount"
                :min="0"
                :controls="false"
                style="width: 100%"
                @change="calculateDefectRate(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="不合格数量" align="center" width="90">
            <template #default="{ row }">
              <el-input-number
                v-model="row.defectCount"
                :min="0"
                :max="row.sampleCount"
                :controls="false"
                style="width: 100%"
                @change="calculateDefectRate(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="不良率" align="center" width="80">
            <template #default="{ row }">
              {{ row.defectRate || '0%' }}
            </template>
          </el-table-column>
          <el-table-column label="实际测量记录" align="center" min-width="150">
            <template #default="{ row }">
              <el-input v-model="row.measurement" placeholder="请输入测量记录"/>
            </template>
          </el-table-column>
          <el-table-column label="判定结果" align="center" width="120">
            <template #default="{ row }">
              <el-select v-model="row.result" placeholder="请选择">
                <el-option label="合格" value="合格"/>
                <el-option label="不合格" value="不合格"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80" fixed="right">
            <template #default="{ $index }">
              <el-button
                link
                type="danger"
                @click="removeRow($index)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          plain
          @click="addRow"
          style="margin-top: 10px; width: 100%"
          :icon="Plus"
        >
          添加检验项目
        </el-button>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="结果" prop="result">
            <el-select v-model="formData.result" placeholder="请选择">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验人员" prop="checkUserId">
            <cascader-user v-model="formData.checkUserId" placeholder="请选择检验人员"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="复核人员" prop="reviewUserId">
            <cascader-user v-model="formData.reviewUserId" placeholder="请选择复核人员"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="2"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附件 URL" prop="fileUrl">
            <upload-file v-model="formData.fileUrl" :isShowTip="false"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

</template>
<script setup lang="ts">
import {CheckIn, CheckInApi} from '@/api/erp/check/in'
import {Delete, Plus} from '@element-plus/icons-vue'
import ErpSelectSupplier from "@/views/erp/purchase/supplier/components/ErpSelectSupplier.vue";

/** ERP 入库检验 表单 */
defineOptions({name: 'CheckInForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  no: undefined,
  linkNo: undefined,
  linkId: undefined,
  linkType: undefined,
  count: undefined,
  supplierId: undefined,
  checkTime: undefined,
  productData: undefined,
  checkData: undefined,
  result: undefined,
  checkUserId: undefined,
  reviewUserId: undefined,
  status: undefined,
  remark: undefined,
  fileUrl: undefined
})
const formRules = reactive({
  result: [{required: true, message: '判断结果不能为空', trigger: 'blur'}],
  linkNo: [{required: true, message: '关联单号不能为空', trigger: 'blur'}],
  checkTime: [{required: true, message: '检验时间不能为空', trigger: 'blur'}],
  checkUserId: [{required: true, message: '检验人员不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

// 产品数据表格定义
interface ProductDataItem {
  name: string // 名称
  quantity: number // 数量
  performance: string // 性能
  size: string // 尺寸
  sampleCount: number // 抽检数量
  defectCount: number // 不合格数量
  defectRate: string // 不良率
  result: string // 判定结果
}

const productData = ref<ProductDataItem[]>([])

// 检验数据表格定义
interface CheckDataItem {
  item: string // 检验项目
  standard: string // 标准
  sampleCount: number // 抽检数量
  defectCount: number // 不合格数量
  defectRate: string // 不良率
  measurement: string // 实际测量记录
  result: string // 判定结果
}

const checkData = ref<CheckDataItem[]>([])

// 监听 formData.count 变化,同步到两个表格的抽检数量
watch(
  () => formData.value.count,
  (newCount) => {
    const count = Number(newCount) || 0
    // 同步到产品数据表格
    productData.value.forEach(row => {
      row.sampleCount = count
      // 重新计算不良率
      calculateProductDefectRate(row)
    })
    // 同步到检验数据表格
    checkData.value.forEach(row => {
      row.sampleCount = count
      // 重新计算不良率
      calculateDefectRate(row)
    })
  }
)

/** 初始化检验数据模板 */
const initCheckData = () => {
  return [
    {
      item: '外观',
      standard: '依据【检验依据】中的标准',
      sampleCount: 0,
      defectCount: 0,
      defectRate: '0%',
      measurement: '',
      result: ''
    },
    {
      item: '包装、标识',
      standard: '包装应防潮、防尘、清洁、干燥、无粉尘、无有害物质；标志应有产品名称、规格、型号、出产日期、批号、包装箱数量、检验合格证书、制造厂商名称、ROHS标识：',
      sampleCount: 0,
      defectCount: 0,
      defectRate: '0%',
      measurement: '',
      result: ''
    },
    {
      item: 'ROHS',
      standard: 'ROHS报告真实有效；拆解成分真实有效',
      sampleCount: 0,
      defectCount: 0,
      defectRate: '0%',
      measurement: '',
      result: ''
    },
    {
      item: '装配',
      standard: '与互配部件装配良好，无不良反应',
      sampleCount: 0,
      defectCount: 0,
      defectRate: '0%',
      measurement: '',
      result: ''
    },
    {
      item: '性能要求',
      standard: '',
      sampleCount: 0,
      defectCount: 0,
      defectRate: '0%',
      measurement: '',
      result: ''
    },
    {
      item: '尺寸（cm）',
      standard: '',
      sampleCount: 0,
      defectCount: 0,
      defectRate: '0%',
      measurement: '',
      result: ''
    }
  ]
}

/** 添加产品行 */
const addProductRow = () => {
  productData.value.push({
    name: '',
    quantity: 0,
    performance: '',
    size: '',
    sampleCount: 0,
    defectCount: 0,
    defectRate: '0%',
    result: ''
  })
}

/** 删除产品行 */
const removeProductRow = (index: number) => {
  productData.value.splice(index, 1)
}

/** 计算产品不良率 */
const calculateProductDefectRate = (row: ProductDataItem) => {
  if (row.sampleCount > 0 && row.defectCount >= 0) {
    const rate = ((row.defectCount / row.sampleCount) * 100).toFixed(2)
    row.defectRate = rate + '%'
  } else {
    row.defectRate = '0%'
  }
}

/** 添加检验项目行 */
const addRow = () => {
  checkData.value.push({
    item: '',
    standard: '',
    sampleCount: 0,
    defectCount: 0,
    defectRate: '0%',
    measurement: '',
    result: ''
  })
}

/** 删除检验项目行 */
const removeRow = (index: number) => {
  checkData.value.splice(index, 1)
}

/** 计算不良率 */
const calculateDefectRate = (row: CheckDataItem) => {
  if (row.sampleCount > 0 && row.defectCount >= 0) {
    const rate = ((row.defectCount / row.sampleCount) * 100).toFixed(2)
    row.defectRate = rate + '%'
  } else {
    row.defectRate = '0%'
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CheckInApi.getCheckIn(id)

      // 解析 JSON 产品数据
      if (formData.value.productData) {
        try {
          productData.value = JSON.parse(formData.value.productData as string)
        } catch (e) {
          console.error('产品数据解析失败:', e)
          productData.value = []
        }
      }

      // 解析 JSON 检验数据
      if (formData.value.checkData) {
        try {
          checkData.value = JSON.parse(formData.value.checkData as string)
        } catch (e) {
          console.error('检验数据解析失败:', e)
          checkData.value = initCheckData()
        }
      } else {
        // 修改时如果没有数据，初始化默认数据
        checkData.value = initCheckData()
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时，初始化默认检验项目
    checkData.value = initCheckData()
  }
}

/** 从采购入库打开检验表单 */
const openWithPurchaseIn = async (purchaseInData: any) => {
  dialogVisible.value = true
  dialogTitle.value = '新增检验'
  formType.value = 'create'
  resetForm()

  // 设置关联信息
  formData.value.linkId = purchaseInData.id
  formData.value.linkNo = purchaseInData.no
  formData.value.linkType = '采购入库' // 关联类型:采购入库
  formData.value.supplierId = purchaseInData.supplierId
  formData.value.count = purchaseInData.totalCount

  // 将采购入库的产品项转换为检验的产品数据
  if (purchaseInData.items && purchaseInData.items.length > 0) {
    productData.value = purchaseInData.items.map((item: any) => ({
      name: item.productName || '',
      quantity: item.count || 0,
      performance: '',
      size: '',
      sampleCount: item.count || 0,
      defectCount: 0,
      defectRate: '0%',
      result: ''
    }))
  }

  // 初始化默认检验项目
  checkData.value = initCheckData()
}

defineExpose({open, openWithPurchaseIn}) // 提供 open 和 openWithPurchaseIn 方法

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CheckIn
    // 将产品数据表格转换为 JSON 字符串
    data.productData = JSON.stringify(productData.value)
    // 将检验数据表格转换为 JSON 字符串
    data.checkData = JSON.stringify(checkData.value)

    if (formType.value === 'create') {
      await CheckInApi.createCheckIn(data)
      message.success(t('common.createSuccess'))
    } else {
      await CheckInApi.updateCheckIn(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    linkNo: undefined,
    linkId: undefined,
    linkType: undefined,
    count: undefined,
    supplierId: undefined,
    checkTime: undefined,
    productData: undefined,
    checkData: undefined,
    result: undefined,
    checkUserId: undefined,
    reviewUserId: undefined,
    status: undefined,
    remark: undefined,
    fileUrl: undefined
  }
  // 重置产品数据表格
  productData.value = []
  // 重置检验数据表格（不清空，保持默认模板）
  checkData.value = []
  formRef.value?.resetFields()
}

</script>
